package com.key.gradle.test.web;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.key.gradle.test.request.UserLogin;

@Controller
public class IndexController {

	private final Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	@Resource(name="redisTemplate")
	private HashOperations<String, String, Object> hops;
	
	public RedisTemplate<Object, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(ModelMap model) {

		logger.debug("index() is executed!");

		model.put("title", "Gradle Spring Mvc Java Config");
		model.put("msg", "Hello Gradle");
		
		return "index";
	}
	
	@RequestMapping(value = "/{path}", method = RequestMethod.GET)
	public String path(@PathVariable String path) {
		logger.debug("path(/{}) is executed!", path);
		return "index";
	}
	
//	@RequestMapping(value = "/login", method = RequestMethod.GET)
//	public String login() {
//		return "login";
//	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request, @RequestBody UserLogin user) {
		
		logger.info(user.toString());
		Map<String, Object> response = new HashMap<String, Object>();
		response.put("id_token", "xxx");
		
		return response;
	}
	
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> test() {
		
		String key = "redis:test:token";
		Map<String, Object> tokenHash = hops.entries(key);
		if (tokenHash == null || tokenHash.isEmpty()) {
			Map<String, Object> response = new HashMap<String, Object>();
			response.put("id_token", System.currentTimeMillis());
			hops.putAll(key, response);
			redisTemplate.expire(key, 5, TimeUnit.SECONDS);
			
			return response;
		} else {
			return tokenHash;
		}
	}
	
}
